<template>
	<div class="per-container">
		<div class="permissionChat">
			<slot />
			<div class="h1">
				{{$t("开启权限")}}
			</div>

			<div class="h2">
				{{$t("开启并允许以下权限,使用完整消息功能")}}
			</div>
			<div class="item">
				<div class="icon">
					<image src="/static/p3.png" mode="widthFix" style="width: 100%;"></image>
					<image src="/static/p5.png" v-if="!camera" class="state-error" mode="widthFix"
						style="width: 30rpx;">
					</image>
				</div>
				<div class="info">
					<div class="title1">{{$t("相机")}}</div>
					<div class="title2">{{$t("视频沟通，面对面交流")}}</div>
				</div>
				<div class="state" v-if="camera">
					<image src="/static/p4.png" mode="widthFix" style="width: 100%;"></image>
				</div>
				<div v-else class="btn" @click="promptToOpenSettings">{{$t("开启")}}</div>
			
			</div>
			<div class="item">
				<div class="icon">
					<image src="/static/p2.png" mode="widthFix" style="width: 100%;"></image>
					<image src="/static/p5.png" v-if="!record" class="state-error" mode="widthFix"
						style="width: 30rpx;">
					</image>
				</div>
				<div class="info">
					<div class="title1">{{$t("麦克风")}}</div>
					<div class="title2">{{$t("语音沟通，交流更高效")}}</div>
				</div>
				<div class="state" v-if="record">
					<image src="/static/p4.png" mode="widthFix" style="width: 100%;"></image>
				</div>
				<div v-else class="btn" @click="startRecordPermission">{{$t("开启")}}</div>

			</div>

		</div>
	</div>
</template>

<script>
	import permision from "@/js_sdk/wa-permission/permission.js"
	
	export default {
		data() {
			return {
				platform: "",
				notice: false,
				record: false,
				camera:false,
				window: false
			}
		},
		created() {
			const systemInfo = uni.getSystemInfoSync();
			if(uni.getStorageSync('platform')){
				this.platform = uni.getStorageSync('platform');
			}else{
				this.platform = systemInfo.platform;
			}

			// #ifdef APP-PLUS
			this.checkRecordPermission()
			this.checkPhotoPermission()
			// #endif
		},
		methods: {
			 checkPhotoPermission() {		
				  if (this.platform === 'android') {
					    const permissions = ['android.permission.CAMERA']
						const mainActivity = plus.android.runtimeMainActivity();
						const PackageManager = plus.android.importClass('android.content.pm.PackageManager');
						permissions.forEach(permission => {
						 const hasPermission = mainActivity.checkSelfPermission(permission) === PackageManager.PERMISSION_GRANTED;
							 if (!hasPermission) {
								this.camera=false
								uni.setStorageSync('CAMERA_permission', 0);
								//this.promptToOpenSettings(); // 引导用户前往设置
							 } else {
							 console.log(`${permission} 权限已开启`);
							 this.camera=true
							 uni.setStorageSync('CAMERA_permission', 1);
							}
						});
				  }else if(this.platform === 'ios'){
					    const AVCaptureDevice = plus.ios.import('AVCaptureDevice');
					    const status = AVCaptureDevice.authorizationStatusForMediaType('vide'); // "vide" 表示摄像头权限
						// 状态解释：
						  // 0 = 未知；1 = 未授权；2 = 拒绝；3 = 授权
						if(status === 3){
							console.log('摄像头权限已授权');
							this.camera=true
							uni.setStorageSync('CAMERA_permission', 1);
						}else{
							console.log('摄像头权限未授权，引导用户开启权限');
							this.camera=false
							uni.setStorageSync('CAMERA_permission', 0);
						} 
				  }
			},
			promptToOpenSettingsIos(){
							 var app = plus.ios.invoke('UIApplication', 'sharedApplication');
							 var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
							 plus.ios.invoke(app, 'openURL:', setting);
							 plus.ios.deleteObject(setting);
							 plus.ios.deleteObject(app);
							
			},
			promptToOpenSettings() {
				 if (this.platform === 'android') {
					const Intent = plus.android.importClass('android.content.Intent');
					const Uri = plus.android.importClass('android.net.Uri');
					const mainActivity = plus.android.runtimeMainActivity();
								
					const intent = new Intent();
					intent.setAction('android.settings.APPLICATION_DETAILS_SETTINGS');
					const uri = Uri.fromParts('package', mainActivity.getPackageName(), null);
					intent.setData(uri);
								
					mainActivity.startActivity(intent);
				 }else if(this.platform === 'ios'){
				    this.promptToOpenSettingsIos()
				 }
			   
			},
			
			//检查悬浮窗口
			checkWindowPermission() {
				if (this.platform != 'ios') {
					let main = plus.android.runtimeMainActivity();
					let pkName = main.getPackageName()
					let Settings = plus.android.importClass('android.provider.Settings')
					let Uri = plus.android.importClass('android.net.Uri')
					let Intent = plus.android.importClass('android.content.Intent')
					let intent = new Intent(
						'android.settings.action.MANAGE_OVERLAY_PERMISSION',
						Uri.parse('package:' + pkName)
					)
					// 检测悬浮窗  
					if (!Settings.canDrawOverlays(main)) {
						this.window = false
						uni.setStorageSync('xuanfuchuang_permission', 0);
					} else {
						this.window = true
						uni.setStorageSync('xuanfuchuang_permission', 1);
					}
				}
			},
			//开启悬浮窗权限
			goWindowSetting() {
				let main = plus.android.runtimeMainActivity();
				let pkName = main.getPackageName()
				let Settings = plus.android.importClass('android.provider.Settings')
				let Uri = plus.android.importClass('android.net.Uri')
				let Intent = plus.android.importClass('android.content.Intent')
				let intent = new Intent(
					'android.settings.action.MANAGE_OVERLAY_PERMISSION',
					Uri.parse('package:' + pkName)
				)

				main.startActivityForResult(intent, 5004) // 转跳到悬浮窗设置  
			},
			//检查通知权限
			checkNoticePermission() {

				// #ifdef APP-PLUS
				if (plus.os.name == 'Android') {
					var main = plus.android.runtimeMainActivity();
					var pkName = main.getPackageName();
					var uid = main.getApplicationInfo().plusGetAttribute("uid");
					var NotificationManagerCompat = plus.android.importClass(
						"android.support.v4.app.NotificationManagerCompat");
					if (NotificationManagerCompat == null) {
						NotificationManagerCompat = plus.android.importClass(
							"androidx.core.app.NotificationManagerCompat");
					}
					var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();
					console.log(areNotificationsEnabled)
					if (!areNotificationsEnabled) {
						uni.setStorageSync('message_permission', 0);
						this.notice = false
					} else {
						uni.setStorageSync('message_permission', 1);
						this.notice = true
					}
				} else if (plus.os.name == 'iOS') {
					var isOn = undefined;
					var types = 0;
					var app = plus.ios.invoke('UIApplication', 'sharedApplication');
					var settings = plus.ios.invoke(app, 'currentUserNotificationSettings');
					if (settings) {
						types = settings.plusGetAttribute('types');
						plus.ios.deleteObject(settings);
					} else {
						types = plus.ios.invoke(app, 'enabledRemoteNotificationTypes');
					}
					plus.ios.deleteObject(app);
					isOn = (0 != types);
					if (isOn == false) {
						uni.setStorageSync('message_permission', 0);
						this.notice = false
					} else {
						uni.setStorageSync('message_permission', 1);
						this.notice = true
					}
				}
				// #endif 
			},
			//开启通知权限
			goNoticeSetting() {
				// #ifdef APP-PLUS
				if (plus.os.name == 'Android') {
					var main = plus.android.runtimeMainActivity();
					var pkName = main.getPackageName();
					var uid = main.getApplicationInfo().plusGetAttribute("uid");
					var NotificationManagerCompat = plus.android.importClass(
						"android.support.v4.app.NotificationManagerCompat");
					if (NotificationManagerCompat == null) {
						NotificationManagerCompat = plus.android.importClass(
							"androidx.core.app.NotificationManagerCompat");
					}
					var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();
					console.log(areNotificationsEnabled)

					var Intent = plus.android.importClass('android.content.Intent');
					var Build = plus.android.importClass("android.os.Build");
					if (Build.VERSION.SDK_INT >= 26) {
						var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
						intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
					} else if (Build.VERSION.SDK_INT >= 21) {
						var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
						intent.putExtra("app_package", pkName);
						intent.putExtra("app_uid", uid);
					} else {
						intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
						var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
						intent.setData(uri);
					}
					main.startActivity(intent);
				} else if (plus.os.name == 'iOS') {
					var app = plus.ios.invoke('UIApplication', 'sharedApplication');
					var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
					plus.ios.invoke(app, 'openURL:', setting);
					plus.ios.deleteObject(setting);
					plus.ios.deleteObject(app);
				}
				// #endif 
			},
			//检查麦克风权限
			checkRecordPermission() {
				if (plus.os.name === "Android") {
					// Android环境下检查权限
					const main = plus.android.runtimeMainActivity();
					const PackageManager = plus.android.importClass("android.content.pm.PackageManager");
					const permission = "android.permission.RECORD_AUDIO";
					const hasPermission = plus.android.runtimeMainActivity().checkSelfPermission(permission);

					if (hasPermission === PackageManager.PERMISSION_GRANTED) {
						console.log("麦克风权限已授权");
						this.record = true;
						uni.setStorageSync('record_permission', 1);
					} else {
						uni.setStorageSync('record_permission', 0);
						console.log("麦克风权限未授权");
						// 跳转到应用设置
						this.record = false;
					}
				} else if (plus.os.name === "iOS") {
					// iOS 环境下检查权限
					this.requestIosPermission2('record')
				}
			},
			//先模拟录音开启权限
			startRecordPermission() {
				console.log('模拟录音开启权限')
				
				//模拟录音
				if (this.platform != 'ios') {
					const recorderManager = uni.getRecorderManager();
					const options = {
						duration: 60000, // 最长录音时间，单位 ms，默认为 60000（1分钟）
						sampleRate: 44100, // 采样率
						numberOfChannels: 1, // 录音通道数
						encodeBitRate: 192000, // 编码码率
						format: 'mp3', // 音频格式 (mp3、aac等)
					};
					recorderManager.start(options);
					setTimeout(() => {
						recorderManager.stop();
					}, 500)
				
					// 监听录音错误
					recorderManager.onError((err) => {
						console.error('录音错误: ', JSON.stringify(err));
						this.goRecordSetting();
					});
				}else{
					console.log('跳转录音setting')
					this.goRecordSetting();
				}
			},
			goRecordSetting() {
				if (this.platform != 'ios') {

					const Intent = plus.android.importClass("android.content.Intent");
					const Settings = plus.android.importClass("android.provider.Settings");
					const Uri = plus.android.importClass("android.net.Uri");
					const main = plus.android.runtimeMainActivity();
					const intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
					const uri = Uri.fromParts("package", main.getPackageName(), null);
					intent.setData(uri);
					main.startActivity(intent);
				} else {
					var avaudiosession = plus.ios.import("AVAudioSession");
					var avaudio = avaudiosession.sharedInstance();
					console.log(avaudio)
					avaudio.requestRecordPermission(() => {
						console.log('回调完成');
					});

					var app = plus.ios.invoke('UIApplication', 'sharedApplication');
					var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
					plus.ios.invoke(app, 'openURL:', setting);
					plus.ios.deleteObject(setting);
					plus.ios.deleteObject(app);

				}

			},
			
			//ios麦克风权限
			async requestIosPermission2(id) {
				var that = this
				var result = await permision.judgeIosPermission(id)
				console.log(result)
				if (result == false) {
					that.record = false
					that.record_quanxian = "麦克风未获得授权"
					uni.setStorageSync('record_permission', 0);
				} else {
					that.record = true
					that.record_quanxian = "麦克风已获得权限"
					uni.setStorageSync('record_permission', 1);
				}
			},
		}
	}
</script>

<style lang="less">
	.per-container {
		position: fixed;
		width: 100%;
		height: 100%;
		left: 0;
		top: 0;
		background: rgba(0, 0, 0, 0.3);
		backdrop-filter: blur(5rpx);
	}

	.permissionChat {
		border-radius: 42rpx;
		position: fixed;
		background: linear-gradient(to bottom, #37D08B, #F6F7F9 40%);
		width: 700rpx;
		padding: 30rpx;
		left: 50%;
		top: 50%;
		z-index: 999;
		transform: translate3d(-50%, -50%, 0);
		box-sizing: border-box;

		.item {
			padding: 30rpx 20rpx;
			box-sizing: border-box;
			background-color: #fff;
			box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
			border-radius: 23rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 16rpx;

			.title1 {
				font-weight: bold;
				color: #3d3d3d;
				font-weight: bold;
				margin-bottom: 4rpx;
				font-size: 35rpx;
			}

			.title2 {
				color: #666;
				font-size: 28rpx;
			}

			.info {
				width: 80%;
				padding-left: 24rpx;
				box-sizing: border-box;
			}

			.icon {
				width: 89rpx;
				height: 89rpx;
				border-radius: 50%;
				flex-shrink: 0;
				position: relative;
			}

			.state-error {
				position: absolute;
				right: 0;
				bottom: 0;
			}

			.state {
				width: 46rpx;
				height: 46rpx;
				flex-shrink: 0;
				margin-right: 25rpx;
			}

			.btn {
				flex-shrink: 0;
				color: #16C276;
				font-weight: bold;
				font-size: 30rpx;
				background-color: #F5F5F5;
				border-radius: 50rpx;
				min-width: 130rpx;
				height: 70rpx;
				display: flex;
				align-items: center;
				padding: 0 20rpx;
				justify-content: center;
			}
		}

		.h1 {
			font-size: 40rpx;
			font-weight: bold;
			color: #fff;
			text-align: center;
		}

		.h2 {
			border-radius: 42rpx;
			background-color: #5FD09E;
			text-align: center;
			color: #fff;
			padding: 10rpx;
			margin: 24rpx 0;
			font-size: 32rpx;
		}
	}
</style>